<?php
// +-------------------------------------------------------------------
// | 
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Kcdns\Admin\Controller;
use Kcdns\Admin\Common\ModelCfg;

/**
 * 模型管理
 */
class ModelController extends CommonController
{

    protected $listWhere = [
        'model.extend' => [
            'neq',
            0
        ]
    ];

    public function cfgx ()
    {

        // 文档模型配置
        if (I('get.model.name'))
        {
            $_GET['id'] = "document/model/" . I('get.model.name');
        }

        // 所有配置项
        $all = M('config')->field('name')->where([
            'name' => [
                'like',
                'MODEL_CFG_%'
            ]
        ])->order('name ASC')->select();
        $ids = [];
        foreach ($all as $v)
        {
            $ids[] = substr($v['name'], strlen('MODEL_CFG_'));
        }

        // 删除
        if (I('get.del'))
        {
            M('config')->field('name')->where([
                'name' => 'MODEL_CFG_' . str_replace('|', '/', I('get.id'))
            ])->delete();
        }

        $id = I('id') or $id = cookie('MODEL_CFG_ID') or $id = $ids[0];
        $id = str_replace('|', '/', $id);
        $ids[] = $id;
        $cfg = new ModelCfg($id, '', true);

        // 保存
        if (IS_POST)
        {
            $cfg->save($id, I('post.cfg_json_string')) && D('config')->clear() ? $this->success('保存成功') : $this->error('保存失败');
        }

        // 文档模型自动补全关联表
        if (I('get.model.name') && ! $cfg->joinTable)
        {
            $cfg->joinTable or $cfg->configOri = [
                'join_table' => [
                    [
                        'table' => 'document_' . I('get.model.name'),
                        'on' => 'document.id=document_' . 'document_' . I('get.model.name') . '.id'
                    ]
                ],
                'list_grid' => [],
                'form_field' => []
            ];
            $cfg->joinTable = [
                [
                    'table' => 'document_' . I('get.model.name'),
                    'on' => 'document.id=document_' . 'document_' . I('get.model.name') . '.id'
                ]
            ];
        }

        // 当前配置使用到的表和字段
        $fields = [
            $cfg->table => M($cfg->table)->getDbFields()
        ];

        $tables=[];
        foreach ($cfg->joinTable as $v)
        {
            if (isset($tables[$v['table']])) {
                $tables[$v['table']] += 1;
                $count = $tables[$v['table']];
            } else {
                $count = '';
                $tables[$v['table']] = 1;
            }
            $fields[$v['table'].$count] = M($v['table'])->getDbFields();
        }

        // 相关表的完整字段信息, 用于自动补全
        $fieldDetails = [];
        foreach ($fields as $table => $v)
        {
            $fieldDetails[$table] = M()->query("select COLUMN_NAME,column_comment from information_schema.COLUMNS where table_name = '" . C('DB_PREFIX') . "$table'");
        }

        // 所有表
        $result = M()->query("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_SCHEMA = '" . C('DB_NAME') . "'");
        $tables = [];
        foreach ($result as $row)
        {
            $t = substr($row['TABLE_NAME'], strlen(C('DB_PREFIX')));
            $tables[] = [
                $t,
                $t
            ];
        }

        $this->assign('id', $id);
        $this->assign('all', array_unique($ids));
        $this->assign('cfgJosn', $cfg->configOri);
        $this->assign('fields', $fields);
        $this->assign('fieldDetails', $fieldDetails);
        $this->assign('tables', $tables);
        $this->display();
    }
}
